﻿using System;
using System.Device.Location;
using System.Diagnostics;
using System.Threading.Tasks;
using Amicus_Place_Finder;

public class LocationService
{
    GeoCoordinateWatcher _watcher;
    public GeoCoordinate CurrentLocation;
    public event EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>> PositionChanged;

    public LocationService()
    {
        _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
        _watcher.MovementThreshold = 10; // 10 meters
        _watcher.StatusChanged +=
            new EventHandler<GeoPositionStatusChangedEventArgs>(OnStatusChanged);
        _watcher.PositionChanged +=
            new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(OnPositionChanged);
        _watcher.Start();
    }

    void OnStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
    {
        if (SettingUtils.Settings.IsLocationServiceEnabled)
        {
            if (e.Status == GeoPositionStatus.Disabled)
                Debug.WriteLine("The location service is currently turned off.");
            else if (e.Status == GeoPositionStatus.NoData)
                Debug.WriteLine("No location data is currently available. Try again later.");
        }
    }

    void OnPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
    {
        try
        {
            if (SettingUtils.Settings.IsLocationServiceEnabled)
            {
                CurrentLocation = e.Position.Location;
                PositionChanged(sender, e);
            }
            else
            {
                CurrentLocation = new GeoCoordinate(0,0,0);
                PositionChanged(sender, e);
            }
        }
        catch { }
    }

    public Task<GeoCoordinate> WaitForChanges()
    {
       // if (SettingUtils.Settings.IsLocationServiceEnabled)
        //{
            var tcs = new TaskCompletionSource<GeoCoordinate>();
            _watcher.PositionChanged += (a1, e1) =>
            {
                if (SettingUtils.Settings.IsLocationServiceEnabled)
                {
                    CurrentLocation = e1.Position.Location;
                    tcs.TrySetResult(e1.Position.Location);
                }
                else
                {
                    CurrentLocation = new GeoCoordinate(0, 0, 0);
                    tcs.TrySetResult(e1.Position.Location);
                }
            };
            return tcs.Task;
        //}
        
    }

}